package org.vectrics.user.web.struts;

import javax.servlet.jsp.JspException;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.vectrics.DataException;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.Request;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;
import org.vectrics.user.Person;


abstract public class PrepareUserEditAction extends VectricsStrutsAction {

	private transient static Logger log = Logger.getLogger(PrepareUserEditAction.class);

	protected abstract UserProfileForm createForm();	
	
	public String doExecute(VectricsActionData actionData) throws JspException {
		log.info("execute()");
		ActionForm form = actionData.getForm();
		Request request = actionData.getRequest();
		
		UserProfileForm profileForm = null;
		if (form == null) {
			profileForm = (UserProfileForm)form;
		}
		
		if (profileForm == null) {
			profileForm = createForm();
		}
		
		Person user = getPersonToEdit(request, actionData.getAuthPerson());
		profileForm.setUserId(user.getId().toString());
		profileForm.setFirstName(user.getFirstName());
		profileForm.setLastName(user.getLastName());
		if (user.getUser() != null) {
			profileForm.setUserName(user.getUser().getUserName());
			profileForm.setPassword(user.getUser().getPassword());
			profileForm.setPassword2(user.getUser().getPassword());
		}
		
		return ("success");
	}
	
	protected Person getPersonToEdit(Request request, Person authPerson) throws JspException {
		log.debug("getUserToEdit() - called");
		String userId = request.getParameter("userId");
		if (userId == null) {
			userId = request.getParameter("user");
		}
		if (userId == null) {
			try {
				Person user = authPerson;
				userId = user.getId().toString();
			}
			catch (Exception ex) {
				log.error("Exception finding auth user", ex);
				throw new JspException("Exception finding auth user", ex);
			}
		}

		log.debug("getUserToEdit() - getting user: " + userId);
		Person appUser = null;
		try {
			appUser = CoreServiceLocator.getPersonService().findPersonById(new Long(userId));
		}
		catch (DataException de) {
			throw new JspException("DataException finding user", de);
		}

		return (appUser);
	}

}
